<template>
  <Container class="mobile-form-modal">
    <div class="mobile-form-modal-inner">
      <div class="title" style="margin: 0">
        {{ $t("form.updateResume.title") }}
      </div>
      <Swiper ref="SwiperRef" :allowTouchMove="false" :space-between="50">
        <SwiperSlide>
          <a-form class="form" :model="formState" ref="form1Ref">
            <a-form-item
              class="form-item"
              :label="$t('form.updateResume.form_item_1_label')"
              name="last_name"
              :rules="[
                {
                  required: true,
                  message: $t('form.updateResume.form_item_1_error'),
                  trigger: 'blur',
                },
              ]"
            >
              <a-input
                :maxlength="30"
                size="large"
                v-model:value.trim="formState.last_name"
              ></a-input>
            </a-form-item>
            <a-form-item
              class="form-item"
              :label="$t('form.updateResume.form_item_2_label')"
              name="first_name"
              :rules="[
                {
                  required: true,
                  message: $t('form.updateResume.form_item_2_error'),
                  trigger: 'blur',
                },
              ]"
            >
              <a-input
                size="large"
                :maxlength="30"
                v-model:value.trim="formState.first_name"
              ></a-input>
            </a-form-item>
            <a-form-item
              class="form-item"
              :label="$t('form.updateResume.form_item_3_label')"
              name="sex"
              :rules="[
                {
                  required: true,
                  message: $t('form.updateResume.form_item_3_error'),
                  trigger: 'blur',
                },
              ]"
            >
              <a-select
                v-model:value="formState.sex"
                :options="globalStore.sexTools.sexSelectOptions"
              ></a-select>
            </a-form-item>
            <a-form-item
              class="form-item"
              :label="$t('form.updateResume.form_item_4_label')"
              name="age"
              :rules="[
                {
                  required: true,
                  message: $t('form.updateResume.form_item_4_error'),
                  trigger: 'blur',
                },
              ]"
            >
              <a-input-number
                :min="0"
                :max="150"
                v-model:value.trim="formState.age"
              />
            </a-form-item>
            <a-form-item
              class="form-item"
              :label="$t('form.updateResume.form_item_5_label')"
              name="country_id"
              :rules="[
                {
                  required: true,
                  message: $t('form.updateResume.form_item_5_error'),
                  trigger: 'blur',
                },
              ]"
            >
              <a-select
                v-model:value="formState.country_id"
                show-search
                :options="countryStore.countrySelectOptions"
                :filter-option="filterOption"
              ></a-select>
            </a-form-item>
            <a-form-item
              class="form-item"
              :label="$t('form.updateResume.form_item_6_label')"
              name="address"
              :rules="[
                {
                  required: true,
                  message: $t('form.updateResume.form_item_6_error'),
                  trigger: 'blur',
                },
              ]"
            >
              <a-input
                :maxlength="50"
                v-model:value.trim="formState.address"
              ></a-input>
            </a-form-item>
          </a-form>
        </SwiperSlide>
        <SwiperSlide>
          <a-form
            class="form form-step-2 swiper_container_2"
            :model="formState"
            ref="form2Ref"
          >
            <a-form-item
              class="form-item checkbox"
              :label="$t('form.updateResume.form_item_7_label')"
              name="language_id"
              :rules="[
                {
                  required: true,
                  message: $t('form.updateResume.form_item_7_error'),
                  trigger: 'blur',
                },
              ]"
            >
              <div class="select-list">
                <div
                  class="select-item"
                  v-for="item in globalStore.languageList"
                  :key="item.id"
                  :class="
                    formState.language_id.includes(item.id + '') ? 'active' : ''
                  "
                  @click="selectCheckItem(item, 'language_id')"
                >
                  {{ item.title }}
                </div>
              </div>
            </a-form-item>
            <a-form-item
              class="form-item checkbox"
              :label="$t('form.updateResume.form_item_8_label')"
              name="education_id"
              :rules="[
                {
                  required: true,
                  message: $t('form.updateResume.form_item_8_error'),
                  trigger: 'blur',
                },
              ]"
            >
              <div class="select-list">
                <div
                  class="select-item"
                  v-for="item in globalStore.educationList"
                  :key="item.id"
                  :class="formState.education_id == item.id ? 'active' : ''"
                  @click="selectCheckItem(item, 'education_id', false)"
                >
                  {{ item.title }}
                </div>
              </div>
            </a-form-item>
            <a-form-item
              class="form-item checkbox"
              :label="$t('form.updateResume.form_item_9_label')"
              name="certificate_id"
              :rules="[
                {
                  required: true,
                  message: $t('form.updateResume.form_item_9_error'),
                  trigger: 'blur',
                },
              ]"
            >
              <div class="select-list">
                <div
                  class="select-item"
                  v-for="item in globalStore.certificateList"
                  :key="item.id"
                  :class="
                    formState.certificate_id.includes(item.id + '')
                      ? 'active'
                      : ''
                  "
                  @click="selectCheckItem(item, 'certificate_id')"
                >
                  {{ item.title }}
                </div>
              </div>
            </a-form-item>
          </a-form>
        </SwiperSlide>
        <SwiperSlide>
          <a-form
            class="form form-step-3 swiper_container_2"
            :model="formState"
            ref="form3Ref"
          >
            <a-form-item
              class="form-item checkbox"
              :label="$t('form.updateResume.form_item_10_label')"
              name="airmodel_id"
              :rules="[
                {
                  required: true,
                  message: $t('form.updateResume.form_item_10_error'),
                  trigger: 'blur',
                },
              ]"
            >
              <div class="select-list">
                <div
                  class="select-item"
                  v-for="item in globalStore.airModelList"
                  :key="item.id"
                  :class="
                    formState.airmodel_id.includes(item.id + '') ? 'active' : ''
                  "
                  @click="selectCheckItem(item, 'airmodel_id')"
                >
                  {{ item.title }}
                </div>
              </div>
            </a-form-item>
          </a-form>
        </SwiperSlide>
      </Swiper>
      <div class="footer-btn">
        <div class="footer-btn-inner">
          <a-button @click="goBack" v-if="!isRegister && currentStep == 0">{{
            $t("btnText.cancel")
          }}</a-button>
          <a-button @click="skipClick" v-if="isRegister && currentStep == 0">{{
            $t("btnText.skip")
          }}</a-button>
          <a-button
            type="primary"
            @click="onClickPrevStep"
            v-if="currentStep != 0"
            >{{ $t("btnText.prev_step") }}</a-button
          >
          <a-button
            type="primary"
            @click="onClickNextStep"
            v-if="currentStep != 2"
            >{{ $t("btnText.next_step") }}</a-button
          >
          <a-button
            class="ensure-btn"
            :class="formIsValid ? '' : 'disabled'"
            type="primary"
            :loading="submiting"
            v-if="currentStep == 2"
            @click="continuePublish"
            >{{ $t("btnText.save") }}</a-button
          >
        </div>
      </div>
    </div>
  </Container>
</template>

<script setup lang="ts">
import { computed, getCurrentInstance, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { postMemberInfo, postUpdateMemberInfo } from "../../api/member";
import { useMemberStore, useGlobalStore, useCountryStore } from "../../store";
import { message } from "ant-design-vue";
import type { UpdateMemberInfoParams } from "../../types/member";
import { useRoute } from "vue-router";

const $t = getCurrentInstance()?.appContext.config.globalProperties.$t;

// ===============store=======================
const memberStore = useMemberStore();
const globalStore = useGlobalStore();
const countryStore = useCountryStore();
const router = useRouter();
const route = useRoute();

const form1Ref = ref();
const form2Ref = ref();
const form3Ref = ref();
const currentStep = ref(0);
const SwiperRef = ref();
const onClickPrevStep = () => {
  currentStep.value--;
  SwiperRef.value.$el.swiper.slidePrev();
};
const isRegister = ref(false);
if (route.query.from == "register") {
  isRegister.value = true;
}
if (!memberStore.profile) {
  if (route.query.form != "register") {
    message.warning($t("message.wait_login"));
    goto("/login");
  }
}

const onClickNextStep = () => {
  if (currentStep.value == 0) {
    form1Ref.value.validate().then(() => {
      currentStep.value = 1;
      SwiperRef.value.$el.swiper.slideNext();
    });
  } else if (currentStep.value == 1) {
    form2Ref.value.validate().then(() => {
      currentStep.value = 2;
      SwiperRef.value.$el.swiper.slideNext();
    });
  }
};

const skipClick = () => {
  goto("/");
};
const { locale } = useI18n();
const initForm = () => {
  if (!memberStore.profile) return;
  formState.value = {
    last_name: memberStore.profile?.last_name || "",
    first_name: memberStore.profile?.first_name || "",
    sex: globalStore.sexTools.getSexById(memberStore.profile?.sex) || "",
    age: memberStore.profile?.age || "",
    country_id:
      countryStore.getCountryById(memberStore.profile?.country_id) || "",
    language_id: memberStore.profile?.language_id?.split(",") || [],
    education_id: memberStore.profile?.education_id || "",
    certificate_id: memberStore.profile?.certificate_id?.split(",") || [],
    airmodel_id: memberStore.profile?.airmodel_id?.split(",") || [],
    address: memberStore.profile?.address,
  };
};

const filterOption = (input: string, option: any) => {
  return option.codes?.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

const selectCheckItem = (
  item: { id: number },
  key: string,
  flag: boolean = true
) => {
  if (flag) {
    let index = formState.value[key].findIndex(
      (value: string) => value == item.id + ""
    );
    if (index >= 0) {
      formState.value[key].splice(index, 1);
    } else {
      formState.value[key].push(item.id + "");
    }
  } else {
    formState.value[key] = item.id + "";
  }
};
const formIsValid = computed(() => {
  let flag = true;
  if (!formState.value.last_name) flag = false;
  if (!formState.value.first_name) flag = false;
  return flag;
});

// Form state
const formState = ref<UpdateMemberInfoParams>({
  last_name: "",
  first_name: "",
  sex: "",
  age: "",
  country_id: "",
  language_id: "",
  education_id: "",
  certificate_id: "",
  airmodel_id: "",
  address: "",
});

const emits = defineEmits(["complete"]);

const submiting = ref(false);
const continuePublish = () => {
  if (!formIsValid.value) return;
  form3Ref.value.validate().then(async () => {
    let params = JSON.parse(JSON.stringify(formState.value));
    params.airmodel_id = params.airmodel_id.join(",");
    params.certificate_id = params.certificate_id.join(",");
    params.language_id = params.language_id.join(",");
    if (isNaN(parseInt(params.sex))) {
      params.sex = globalStore.getSexIdBySexName(params.sex + "");
    }
    if (isNaN(parseInt(params.country_id))) {
      params.country_id = countryStore.getCountryIdByTitle(
        params.country_id + ""
      );
    }
    submiting.value = true;
    let res = await postUpdateMemberInfo(params);
    if (res.code === 200) {
      let res2 = await postMemberInfo();
      if (res2.code === 200) {
        Object.assign(memberStore.profile, res2.data);
        memberStore.profile.last_name = formState.value.last_name;
        memberStore.profile.first_name = formState.value.first_name;
        message.success($t("message.changed_success"));
        submiting.value = false;
      } else {
        submiting.value = false;
        message.error($t("message.error.update"));
      }
    } else {
      submiting.value = false;
      message.error($t("message.error.update"));
    }
    goBack();
  });
};
const goBack = () => {
  if (route.query.from == "register") {
    goto("/");
    return;
  }
  router.go(-1);
};

onMounted(() => {
  initForm();
});
</script>
<style lang="less">
.mobile-form-modal {
  .wrap-container > .wrap-pl {
    padding-bottom: 0 !important;
  }
}
</style>
<style scoped lang="less">
@import url("./common.less");

:deep(.form) {
  .ant-form-item {
    .ant-row {
      justify-content: space-between;
      width: 100%;
      .ant-col {
        padding-bottom: 0;
        flex: 0 0 auto !important;
        .ant-select-selector,
        .ant-input-number {
          border-color: transparent !important;
          box-shadow: 0 0 0 transparent !important;
          input {
            text-align: right;
          }
        }
        .ant-select {
          min-width: 600px;
          text-align: right;
        }
      }
    }
    &.checkbox {
      .ant-row {
        flex-direction: column;
      }
      .select-list {
        margin-top: 61px;
        display: grid;
        grid-template-columns: 1fr 1fr 1fr 1fr;
        gap: 41px;
        font-size: 50px;
        color: #172026;
        .select-item {
          border-radius: 51px 51px 51px 51px;
          border: 1px solid #ccd6de;
          height: 205px;
          display: flex;
          justify-content: center;
          align-items: center;
          text-align: center;
          // padding: 51px;
          line-height: 90px;
          &.active {
            color: #ffffff;
            background: #3d88f2;
            border-color: #3d88f2;
          }
        }
      }
    }
  }
  .ant-form-item-explain-error {
    text-align: right !important;
  }
  &.form-step-2,
  &.form-step-3 {
    .ant-form-item-explain-error {
      text-align: left !important;
    }
  }
}

@media screen and (max-width: 768px) {
  :deep(.swiper_container_2) {
    .ant-row .ant-col {
      width: 100%;
      .ant-form-item-control-input-content {
        & > * {
          flex: 1;
        }
      }
    }
  }
}
</style>
